import { User } from "@/api/interface/index";
import { GlobalStore } from "@/stores";
import type { ElForm, ElInput, MessageHandler } from "element-plus";
import { useRouter } from "vue-router";
import DialogBox from "../../../components/DialogBox";
import { getHome } from "../../../utils/routerUtil";
import Register from "./register";
import { PublicStore } from "@/stores/modules/public";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import { usePhoneCode } from "@/hooks/getPhoneCode";
import { AuthStore } from "@/stores/modules/auth";
import Vcode from "vue3-puzzle-vcode";

const LoginPhone = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		type FormInstance = InstanceType<typeof ElForm>;
		type FormInputInstance = InstanceType<typeof ElInput>;
		const codeInputEl = ref<FormInputInstance>();
		const loginFormRef = ref<FormInstance>();
		const globalStore = GlobalStore();
		const publicStore = PublicStore();
		const authStore = AuthStore();
		const router = useRouter();
		const loading = ref(false);
		const loginRules = reactive({
			mobile: [{ required: true, message: proxy?.$t("login.rules.username"), trigger: "change" }]
		});
		const detail = reactive({
			mobile: "",
			code: ""
		});
		let { getCode, codeStatus } = usePhoneCode(detail);
		const geePhoneCode = () => {
			isShow.value = true;
		};
		const isShow = ref(false);
		const success = () => {
			isShow.value = false;
			getCode();
			codeInputEl.value?.focus();
		};
		onMounted(() => {});
		const login = (formEl: FormInstance) => {
			formEl.validate(async (valid: boolean) => {
				if (!valid) return;
				loading.value = true;
				const err: MessageHandler | string | undefined = await authStore.login({ phone: detail.mobile, code: detail.code });
				if (err != null) {
					loading.value = false;
					return;
				}
				// 默认主页无法访问时导致系统无法使用，暂不启用
				if (globalStore.setting.home.startsWith("http")) {
					let token = "";
					if (RegExp(/\?.+=.*/).test(globalStore.setting.home)) {
						token = `&token=${publicStore.token}`;
					} else {
						token = `?token=${publicStore.token}`;
					}
					let server = globalStore.setting.home + token;
					window.location.href = server;
				} else {
					router.push(getHome());
				}
				// loading.value = false;
			});
		};
		const registerDialog = reactive({
			visible: false,
			detail: { username: "" }
		});
		const submitRegister = () => {
			detail.mobile = registerDialog.detail.username;
			registerDialog.visible = false;
		};
		return () => {
			return (
				<>
					<DialogBox
						class="register-dialog"
						hideFooter
						v-model:visible={registerDialog.visible}
						title={proxy?.$t("login.dialog_title.register")}
						width="1024px"
					>
						{registerDialog.visible ? (
							<Register
								detail={registerDialog.detail as User.ReqUserRegister}
								onBackLogin={() => (registerDialog.visible = false)}
								onSubmit={() => submitRegister()}
							/>
						) : null}
					</DialogBox>
					<el-form model={detail} ref={loginFormRef} rules={loginRules} size="large">
						<el-form-item prop="mobile" class="el-form-username">
							<el-input
								class="pb-2"
								v-model={detail.mobile}
								placeholder={proxy?.$t("login.input_placeholder.username")}
								v-slots={{
									prefix: () => {
										return <span class="iconfont iconuser"></span>;
									}
								}}
							></el-input>
						</el-form-item>
						<el-form-item prop="code">
							<el-input ref={codeInputEl} v-model={detail.code} placeholder="请输入注册验证码">
								{{
									prefix: () => {
										return <span class="iconfont iconbx-barcode" />;
									},
									append: () => {
										return (
											<el-button type="info" loading={codeStatus.countDown > 0} onClick={() => geePhoneCode()}>
												{codeStatus.countDown > 0 ? (
													<span class="text-black">
														<span class="text-red-600">{codeStatus.countDown}</span>秒后重试
													</span>
												) : (
													<span>获取验证码</span>
												)}
											</el-button>
										);
									}
								}}
							</el-input>
						</el-form-item>
					</el-form>
					<div class="login-btn flex" style="margin-top:94px">
						<el-button
							class="flex-1"
							onClick={() => login(loginFormRef.value as FormInstance)}
							size="large"
							type="primary"
							loading={loading.value}
						>
							{proxy?.$t("login.btn.login")}
						</el-button>
					</div>
					<div class="flex justify-center login-panel-register">
						<span>{proxy?.$t("login.text.no_account")} </span>
						<el-link type="primary" onClick={() => (registerDialog.visible = true)}>
							{proxy?.$t("login.link.register")}
						</el-link>
					</div>
					<div class="ext-tips">{proxy?.$t("login.tips.use_chrome")}</div>
					<Vcode show={isShow.value} onSuccess={success} onClose={close} />
				</>
			);
		};
	}
});
export default LoginPhone;
